package com.ruoyi.log;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;

import java.util.Map;
import java.util.concurrent.Callable;

/**
 * @author cc
 * @ClassName: com.xh.common.log
 * @date: 2024/12/27 13:36
 * @Description:
 */
@Slf4j
public class RunableWrapper {

    public static Runnable of(Runnable task){
        Map<String, String> mdcMapping = MDC.getCopyOfContextMap();
        return () ->{
            try {
                MDC.setContextMap(mdcMapping);
                task.run();
            } catch (Exception e) {
               log.warn("RunnableWrapper error", e);
            }finally {
                MDC.clear();
            }
        };
    }

    public static <T> Callable<T> wrap(Callable<T> task) {
        Map<String, String> mdcContext = MDC.getCopyOfContextMap();

        return () -> {
            try {
                if (mdcContext != null) {
                    MDC.setContextMap(mdcContext);
                }
                return task.call();
            } catch (Exception e) {
                log.warn("CallableWrapper error", e);
                throw e;
            } finally {
                MDC.clear();
            }
        };
    }

}
